<script setup lang="ts">
import type { Action, FormInstance } from 'element-plus'

import {
  Delete,
  Edit,
  Plus,
} from '@element-plus/icons-vue'
import { defaultFormData } from '../index'
import FormModal from './AssociationFormModal.vue'
import type {
  CustomDialogInstance,
  IndicatorInfo,
  MeasuringToolsInfo,
  TableColumn,
} from '@/types'
import { indicatorApi, unitManagementApi } from '@/api'
// ------------------use------------------
// #region
const props = defineProps<{
  toolsData: MeasuringToolsInfo
}>()
defineEmits<{
  success: []
  close: []
}>()
useCurrentInstance()
const { withLoading, loading } = useDefineLoading({
  destroyNode: true,
})
const [tableData, setTableData] = useState<any[]>([])
const [formData, setFormData] = useState<any>({
  ...defaultFormData,
})
const [formModalTitle, setFormModalTitle]
  = useState<string>('')
const [unitData, setUnitData] = useState<any[]>([])
// #endregion
// ------------------静态变量------------------
// #region
const columns: TableColumn<IndicatorInfo>[] = [
  {
    key: uuid(),
    label: '测点编码',
    prop: 'indicatorNumber',
    width: '200px',
    fixed: 'left',
  },
  {
    key: uuid(),
    label: '指标名称',
    prop: 'indicatorName',
  },
  {
    key: uuid(),
    label: '指标来源',
    prop: 'source',
    width: '150px',
  },
  {
    key: uuid(),
    label: '计量单位',
    prop: 'unit',
  },
  {
    key: uuid(),
    label: '测点点位号',
    prop: 'indicatorCode',
  },
]

const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef = ref<FormInstance | null>(null)
const modalRef = ref<InstanceType<typeof FormModal>>()

async function open() {
  dialogRef.value?.open?.()
  await nextTick()
  dialogRef.value?.setSaving?.(false)
  formRef.value?.resetFields()
  await nextTick()
  getTableData()
}
function close() {
  dialogRef.value?.close?.()
}
async function deleteData(id: number) {
  const res: Action = await ElMessageBox.confirm(
    '该操作将永久删除该数据，确定删除？',
    '警告',
    {
      type: 'warning',
    },
  ).catch(e => e)

  if (res !== 'confirm')
    return
  try {
    const { code } = await indicatorApi.deleteIndicatorById(id)
    if (code !== 200) {
      ElMessage.info('删除失败，请稍后再试！')
      return
    }
    getTableData()
    ElMessage.success('删除成功！')
  }
  catch (e) {}
}
async function getTableData() {
  const { data: res } = await withLoading(
    indicatorApi.selectIndicatorByToolsId,
  )(props.toolsData.id)
  setTableData(res)
}
function success() {
  getTableData()
}
async function showEditDialog(row: any) {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('编辑')
  setFormData({
    ...defaultFormData,
    ...row,
    pointId: props.toolsData.pointId,
    toolsId: props.toolsData.id,
    indicatorMultiple: row.indicatorMultiple || 1,
  })
}
async function showAddDialog() {
  modalRef.value?.open()
  await nextTick()
  setFormModalTitle('新增')
  setFormData({
    ...defaultFormData,
    pointId: props.toolsData.pointId,
    toolsId: props.toolsData.id,
    indicatorMultiple: 1,
  })
}
async function getUnitData() {
  const { data: res }
    = await unitManagementApi.selectUnitList()
  setUnitData(
    res.map((item: any) => ({ id: uuid(), ...item })),
  )
}

onBeforeMount(() => {
  getUnitData()
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="`关联测点-(${toolsData.code}_${toolsData.name})`"
    need-saving
    width="66%"
    cancel-button-text="关闭"
    :show-confirm-button="false"
    @close="$emit('close')"
  >
    <div
      class="flex-direction overflow flex container"
      style="height: 40vh"
    >
      <view-table
        :loading="loading"
        :columns="columns"
        :data="tableData"
        class="flex-fillRemaining"
      >
        <template #source="{ row }">
          <ElTag v-if="row.source === 0" effect="light">
            手动录入
          </ElTag>
          <ElTag
            v-else-if="row.source === 1"
            type="danger"
            effect="light"
          >
            计量器具录入
          </ElTag>
          <ElTag v-else type="warning" effect="light">
            统计指标录入
          </ElTag>
        </template>
        <template #actions>
          <el-button
            plain
            type="success"
            :icon="Plus"
            @click="showAddDialog"
          >
            新增
          </el-button>
        </template>
        <template #operate="{ row }">
          <TdButton
            title="编辑"
            :icon="Edit"
            type="primary"
            @click="showEditDialog(row)"
          />
          <el-divider direction="vertical" />
          <TdButton
            title="删除"
            :icon="Delete"
            type="danger"
            @click="deleteData(row.id!)"
          />
        </template>
      </view-table>
    </div>
    <FormModal
      ref="modalRef"
      v-model="formData"
      :title="formModalTitle"
      :unit-data="unitData"
      @success="success"
    />
  </CustomDialog>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
